<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>图片压缩工具</title>
		<script src="jquery-2.2.1.min.js"></script>
		<style type="text/css">
			.center-text {
				text-align: center;
			}
			
			.inputfile {
				opacity: 0;
			}

			.lab {
				border-radius: 10px;
				background-color: #cc99ff;
				font-family: 楷体;
				font-size: 24px;
			}
			.estimate{
				border-radius: 10px;
				background-color: #1a8cff;
				font-family: 楷体;
				font-size: 20px;
			}
			.preview{
				border-radius: 10px;
				background-color: #ffffcc;
				font-family: 楷体;
				font-size: 14px;
			}
		</style>
	</head>
	<body>
		<h3 class="center-text">图片压缩工具</h3><br />
		<div class="center-text">
			<input type="file" name="file1" id="file1" class="inputfile" accept="image/*" /><br />
			<label for="file1" class='lab'>1.打开图片</label><br /><br />
			<img src="o.jpg" id="img1" style="width: 300px;"><!-- 图片显示区域大小 -->
			<div class="center-text" id="img_info"></div>
		</div>
		<br />
		<br />
		<div class="center-text">图片尺寸缩放选项</div>
		<div class="center-text">
			<input type="radio" name="size_type" value="default" checked="true" />尺寸不变
			<input type="radio" name="size_type" value="1_2" />1/2
			<input type="radio" name="size_type" value="1_3" />1/3
			<input type="radio" name="size_type" value="1_4" />1/4
			<input type="radio" name="size_type" value="1_6" />1/6
			<input type="radio" name="size_type" value="1_8" />1/8
			<input type="radio" name="size_type" value="2" />2倍
		</div>
		<br />
		<div class="center-text">压缩格式</div>
		<div class="center-text">
			<input type="radio" name="format_type" value="jpeg"  checked="true"/>Jpeg/Jpg
			<input type="radio" name="format_type" value="png" />Png
			<input type="radio" name="format_type" value="webp" />Webp
		</div>
		<br />
		<div class="center-text">
			<button id="estimate" class="estimate" type="button" style="width:120px;height:40px;">2.压缩预测</button>&nbsp;&nbsp;
		</div>
		<br />
		<div id="process" class="center-text" style="display:none;">正在处理，请稍等……</div>
		<div id="result" style="display:none;">
			<div class="center-text" id="result-size"></div><br />
			<div class="center-text" id="compress_info"></div>
			<br />
			<div class="center-text">选择压缩质量</div>
			<div class="center-text">
				<input type="radio" name="q_type" value="100" />100
				<input type="radio" name="q_type" value="99" />99
				<input type="radio" name="q_type" value="98" />98
				<input type="radio" name="q_type" value="97" />97
				<input type="radio" name="q_type" value="96" />96
				<input type="radio" name="q_type" value="95" />95
				<input type="radio" name="q_type" value="93" />93
				<br/>
				<input type="radio" name="q_type" value="90" />90
				<input type="radio" name="q_type" value="80"  checked="true"/>80
				<input type="radio" name="q_type" value="70" />70
				<input type="radio" name="q_type" value="60" />60
				<input type="radio" name="q_type" value="50" />50
				<input type="radio" name="q_type" value="40" />40
				<input type="radio" name="q_type" value="30" />30
			</div>
			<br />
			<div class="center-text">
				<button id="download" class="estimate" type="button" style="width:160px;height:40px;">3.压缩并下载</button>&nbsp;&nbsp;&nbsp;&nbsp;
				<button id="preview" class="preview" type="button" style="width:60px;height:30px;">预览</button>
			</div>
		</div>
		<br />
		<br />
		<div id="showArea">
		提示：1/2表示将图片宽高均缩小为原来二分之一;
		在限制压缩大小的情况下，应避免过度缩小图片尺寸，同时选择合适的压缩质量以达到较好的压缩效果;
		例如:[缩放选择1/2压缩质量40]比[缩放选择1/4压缩质量95]的压缩效果一般会更好。
		</div>
		<div><font color="red">禁止在大分辨率未缩小的情况下，选择大于93的压缩质量进行压缩，可能会造成页面崩溃或卡死。</font></div>
		<br />
		<div class="center-text">本网页工具不会上传用户任何数据，所有数据仅运行在您的电脑上，关闭页面即可清空数据，请放心使用。</div>
		<script>
			var img1_size={width:0,height:0};
			var canvas = document.createElement('canvas');
			
			function getImageSize(url,filesize,save){
				var img = new Image();
				img.src = url;
				img.onload = function(){
					// 打印
					save.width=img.width;
					save.height=img.height;
					document.getElementById("img_info").innerHTML="分辨率："+save.width+" x "+save.height
					+"&nbsp;&nbsp;总像素："+((save.width*save.height)/10000000).toFixed(4)+"千万像素&nbsp;&nbsp;文件大小："
					+(filesize/1024).toFixed(1)+"KB";
				}
			};
			//file extends blob
			function createURL(file) {
				var url = null;
				if (window.createObjectURL != undefined) {
					url = window.createObjectURL(file);
				} else if (window.URL != undefined) { // mozilla(firefox)  
					url = window.URL.createObjectURL(file);
				} else if (window.webkitURL != undefined) { // webkit or chrome  
					url = window.webkitURL.createObjectURL(file);
				}
				return url;
			};
			$("#file1").change(function() {
				var objUrl = createURL(this.files[0]); //获取文件信息
				var filesize=this.files[0].size;
				if (objUrl) {
					$("#img1").attr("src", objUrl);
					getImageSize(objUrl,filesize,img1_size);
				}
				$("#result").hide('slow');
			});
			$("input[name='size_type']").change(function() {
				$("#result").hide('slow');
				
			});
			$("input[name='format_type']").change(function() {
				$("#result").hide('slow');
				
			});
			function add0(m){return m<10?('0'+m):m }
			function getSaveFileName(baseFileName)
			{
				var time = new Date();
				var y = time.getFullYear();
				var m = time.getMonth()+1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return baseFileName+'_'+y+add0(m)+add0(d)+'_'+add0(h)+add0(mm)+add0(s)+".jpg";
			}
			function downLoad(url,baseFileName){
				var oA = document.createElement("a");
				oA.download = getSaveFileName(baseFileName);// 设置下载的文件名，默认是'下载'
				oA.href = url;
				document.body.appendChild(oA);
				oA.click();
				oA.remove(); // 下载之后把创建的元素删除
			}
			function estimate_size(canvas,format,option){
				var size=canvas.toDataURL(format,option);
				return size.length;
			}
			function estimate(){
				var size_type=$("input[name='size_type']:checked").val();
				//console.log("size_type = " + size_type);
				if(size_type=="default"){
					canvas.width = img1_size.width; //
					canvas.height = img1_size.height;
				}else if(size_type=="default"){
					canvas.width = img1_size.width; //
					canvas.height = img1_size.height;
				}else if(size_type=="1_2"){
					canvas.width = img1_size.width/2; //
					canvas.height = img1_size.height/2;
				}else if(size_type=="1_3"){
					canvas.width = img1_size.width/3; //
					canvas.height = img1_size.height/3;
				}else if(size_type=="1_4"){
					canvas.width = img1_size.width/4; //
					canvas.height = img1_size.height/4;
				}else if(size_type=="1_6"){
					canvas.width = img1_size.width/6; //
					canvas.height = img1_size.height/6
				}else if(size_type=="1_8"){
					canvas.width = img1_size.width/8; //
					canvas.height = img1_size.height/8;
				}else if(size_type=="2"){
					canvas.width = img1_size.width*2; //
					canvas.height = img1_size.height*2;
				}else{
					canvas.width = 8; //
					canvas.height = 8;
				}
				canvas.width = Math.max(canvas.width,1); //
				canvas.height = Math.max(canvas.height,1);
				//console.log(canvas.width+" x " + canvas.height);
				canvas.style.backgroundColor = '#EEEEEE';
				var ctx=canvas.getContext('2d');
				//ctx.rect(0,0,canvas.width,canvas.height);
				ctx.fillStyle = "#FFFFFF";
				ctx.fillRect(0, 0, canvas.width, canvas.height);
				var img1=document.getElementById('img1');
				ctx.drawImage(img1, 0, 0, img1_size.width, img1_size.height, 0, 0, canvas.width, canvas.height);
				//console.log("size = " + estimate_size(canvas,0.95)/1024/4*3);
				
				$("#result").show('slow');
				
				var compress_info_str="预测图片压缩大小(压缩质量->存储大小):<br/>";
				
				document.getElementById("result-size").innerHTML="目标分辨率："+canvas.width+" x "+canvas.height
				+"   总像素："+((canvas.width*canvas.height)/10000000).toFixed(4)+"千万像素";
				
				var format=getCompressFormat();
				var options = [100,98,96,95,93,90,80,70,60,50,40,30];
				for(let i = canvas.width*canvas.height<5000000?0:4; i < options.length; i++){
					var option=options[i];
					compress_info_str+=option+"&nbsp;->&nbsp;"+ (estimate_size(canvas,format,option/100)/1024/4*3).toFixed(2)+"KB&nbsp;&nbsp;&nbsp;&nbsp;";
					if(i%4==3){
						compress_info_str+="<br />";
					}
					//document.getElementById("compress_info").innerHTML=compress_info_str;
					$("#compress_info").html(compress_info_str);
				}
				compress_info_str+="<br />若以上存储大小均不合适，请选择合适的缩放选项."
				//document.getElementById("compress_info").innerHTML=compress_info_str;
				$("#compress_info").html(compress_info_str);
			};
			function getFileName(){
				var file = $("#file1").val();
 				var pos = file.lastIndexOf("\\");
 				var filename = file.substring(pos+1);
				return filename.lastIndexOf(".")>0? filename.substring(0,filename.lastIndexOf(".")):filename;
 				//var fileextname = filename.substring(filename.lastIndexOf("."), filename.length);
			};
			function getQuality(){
				var q=80;
				var q_type=$("input[name='q_type']:checked").val();
				if(q_type=="100"){
					q=100;
				}else if(q_type=="99"){
					q=99;
				}else if(q_type=="98"){
					q=98;
				}else if(q_type=="97"){
					q=97;
				}else if(q_type=="96"){
					q=96;
				}else if(q_type=="95"){
					q=95;
				}else if(q_type=="93"){
					q=93;
				}else if(q_type=="90"){
					q=90;
				}else if(q_type=="80"){
					q=80;
				}else if(q_type=="70"){
					q=70;
				}else if(q_type=="60"){
					q=60;
				}else if(q_type=="50"){
					q=50;
				}else if(q_type=="40"){
					q=40;
				}else if(q_type=="30"){
					q=30;
				}else{
					q=80;
				}
				return q;
			}
			function getCompressFormat(){
				var format="image/jpeg";
				var format_type=$("input[name='format_type']:checked").val();
				if(format_type=="jpeg"){
					format="image/jpeg";
				}else if(format_type=="png"){
					format="image/png";
				}else if(format_type=="webp"){
					format="image/webp";
				}
				return format;
			}
				$("#estimate").click(function(){
					//$("#process").show('slow');
					estimate();
					//$("#process").hide('slow');
				});
				$("#download").click(function(){
					var q=getQuality();
					var data = canvas.toDataURL(getCompressFormat(),q/100);
					var baseFileName=getFileName();
					downLoad(data,baseFileName);
					//console.log(getFileName());
				});
				$("#preview").click(function(){
					var q=getQuality();
					canvas.toBlob(
					function (blob) {
						//console.log('to blob');
						console.log(blob);
						
						//let binaryData = [];
						//binaryData.push(blob);
						//blob = new Blob(binaryData, { type: 'image/jpeg' });
						
						const url = createURL(blob); 
						window.open(url, '_blank');
					},getCompressFormat(),q/100);
				});
		</script>
	</body>
</html>

